import { getAirLinesApi } from '../../api/index'
import { setPage } from '../../utils/index'
import { STORAGE_KEY } from '../../utils/storage'
import { TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants'
const pageName = TRACER_PAGES['airlines']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    KeyWord: '',
    placeholder: '请输入航空公司名称',
    disabled: false,
    actionName: '取消',
    airLinesHistoryList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init(options)
  },

  onShow: function() {
    setPage(pageName, PRODUCT_CODE)
  },

  init() {

    // 获取 历史航线
    const airLinesHistoryList = wx.getStorageSync(STORAGE_KEY.historyAirLines) || [];
    if(airLinesHistoryList && airLinesHistoryList.length > 0) {
      this.setData({
        airLinesHistoryList
      })
    }

    this.getAirLines()
  },

  getAirLines: function(KeyWord = '') {
    const that = this
    getAirLinesApi({KeyWord}).then(response => {
      const list = that.cleanData(response)
      that.setData({
        list,
        KeyWord
      })
    })
  },

  // 存储搜索历史
  storeAirLinesHistory (airLineInfo) {
      let airLinesHistoryList = wx.getStorageSync(STORAGE_KEY.historyAirLines) || []
      let index = airLinesHistoryList.findIndex(item => item.airCode === airLineInfo.airCode)
      if (index !== -1) { // 搜索航线已经在历史记录中，将其插到第一个
          airLinesHistoryList.splice(index, 1)
      }
      airLinesHistoryList.unshift(airLineInfo)
      const airLinesHistoryListRecently = airLinesHistoryList.slice(0, 5) // 保留最近5条搜索记录
      wx.setStorageSync(STORAGE_KEY.historyAirLines, airLinesHistoryListRecently)
  },

  cleanData: function(list) {
    if(!list) return []
    return list.map(item => {
        return {
            airCode: item.AirCode,
            airCName: item.AirCName,
            airEName: item.AirEName,
            airTName: item.AirTName,
            showName: `${item.AirCode} - ${item.AirCName}`
        }
    })
  },

  handleChange: function(e) {
    const keyword = e.detail.value
    this.getAirLines(keyword)
  },
  cancelSearch: function(e) {
    this.setData({
      KeyWord: ''
    })
    this.getAirLines()
  },
  onBlur: function() {
   
  },
  selectAirLine: function(e) {
    const item = e.currentTarget.dataset.item
    this.storeAirLinesHistory(item)
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('selectAirLineChannel', { data: item});
    wx.navigateBack();
  },
})